package org.xw.service.impl;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.xw.dto.MsgDTO;
import org.xw.mapper.ChatMapper;
import org.xw.mapper.MessageMapper;
import org.xw.pojo.MembersPojo;
import org.xw.pojo.MessagePojo;
import org.xw.service.MessageService;
import org.xw.utils.JWTUtil;
import org.xw.utils.ResponseUtil;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    MessageMapper messageMapper;
    @Resource
    ChatMapper chatMapper;


    /**
     * 查询聊天记录
     *
     * @param httpServletRequest
     * @param msgDTO
     * @return
     */
    @Override
    public ResponseUtil getMsg(HttpServletRequest httpServletRequest, MsgDTO msgDTO) {

        //解析id，确认群成员
        String userId = JWTUtil.analyzeToken(httpServletRequest, "Authorization", "user_id");
        System.out.println(msgDTO);
            if (msgDTO.getIsQw()==1){
                List<MessagePojo> messages = messageMapper.getQwMsg(msgDTO);
                msgDTO.setMessages(messages);
                return ResponseUtil.success(msgDTO);
            }else {
                if (getMember(userId, msgDTO.getChatId()) != null) {
                List<MessagePojo> messages = messageMapper.getMsg(msgDTO);
                System.out.println("messages:"+messages);
                msgDTO.setMessages(messages);
                return ResponseUtil.success(msgDTO);
                }
            }
        return ResponseUtil.error("您已被踢出群聊");
    }

    /**
     * 条件查询聊天记录，日期，内容，成员
     *
     * @param msgDTO
     * @return
     */
    @Override
    public ResponseUtil selectMsg(MsgDTO msgDTO) {
        System.out.println("条件查询消息:"+msgDTO);
        List<MessagePojo> messages = messageMapper.selectMsg(msgDTO);
        System.out.println("条件查询消息结果:"+messages);
        msgDTO.setMessages(messages);
        return ResponseUtil.success(msgDTO);
    }

    /**
     * 先判断消息类型，然后消息存入数据库
     *
     * @param messagePojo
     * @return
     */
    @Override
    public int store(MessagePojo messagePojo) {
        if (messagePojo.getFile() == null) {
            return messageMapper.store(messagePojo);
        }
        return messageMapper.storeFilePath(messagePojo);
    }

    //主要用于判断用户是否在聊天列表中
    @Override
    public MembersPojo getMember(String userId, int chatId) {
        return chatMapper.getMember(userId, chatId);
    }

}
